package com.cyy.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyy.base.exception.CommonError;
import com.cyy.base.exception.LearningException;
import com.cyy.content.mapper.CourseBaseMapper;
import com.cyy.content.mapper.CourseMarketMapper;
import com.cyy.content.mapper.CoursePublishMapper;
import com.cyy.content.mapper.CoursePublishPreMapper;
import com.cyy.content.model.dto.CourseBaseInfoDto;
import com.cyy.content.model.dto.CoursePreviewDto;
import com.cyy.content.model.dto.TeachPlanDto;
import com.cyy.content.model.po.CourseBase;
import com.cyy.content.model.po.CourseMarket;
import com.cyy.content.model.po.CoursePublish;
import com.cyy.content.model.po.CoursePublishPre;
import com.cyy.content.service.CourseBaseService;
import com.cyy.content.service.CoursePublishService;
import com.cyy.content.service.TeachplanService;
import com.cyy.messagesdk.model.po.*;
import com.cyy.messagesdk.service.MqMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程发布 服务实现类
 * </p>
 *
 * @author cyy
 */
@Slf4j
@Service
public class CoursePublishServiceImpl extends ServiceImpl<CoursePublishMapper, CoursePublish> implements CoursePublishService {

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    CourseBaseService courseBaseService;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    TeachplanService teachplanService;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;


    @Autowired
    RedisTemplate redisTemplate;


//    @Autowired
//    MqMessageService mqMessageService;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {
        //获取课程基本信息
        CourseBaseInfoDto courseBaseInfoDto = courseBaseService.getCourseBaseInfo(courseId);
        //获取课程计划信息
        List<TeachPlanDto> teachPlanTree = teachplanService.findTeachPlanTree(courseId);

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        coursePreviewDto.setCourseBase(courseBaseInfoDto);
        coursePreviewDto.setTeachplans(teachPlanTree);
        return coursePreviewDto;
    }

    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        return coursePublishMapper.selectById(courseId);
    }

    @Override
    public CoursePublish getCoursePublishCache(Long courseId) {
        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
        if(jsonObj != null){
            //缓存命中
            String jonString = jsonObj.toString();
            CoursePublish coursePublish = JSON.parseObject(jonString, CoursePublish.class);
            return coursePublish;
        }else {
            //从数据库中查询
            CoursePublish coursePublish = getCoursePublish(courseId);
            //查询完成再存储到redis
            redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish));
            return coursePublish;
        }
    }

    @Override
    public void commitAudit(Long courseId, Long companyId) {
        //约束校验
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //课程审核状态
        String auditStatus = courseBase.getAuditStatus();
        //当前状态为提交不允许再次提交
        if("202003".equals(auditStatus)){
            LearningException.cast("当前为等待审核状态，审核完成可以再次提交。");
        }
        //本机构只允许提交本机构的课程
        if(!courseBase.getCompanyId().equals(companyId)){
            LearningException.cast("不允许提交其它机构的课程。");
        }

        //课程图片是否填写
        if(StringUtils.isEmpty(courseBase.getPic())){
            LearningException.cast("提交失败，请上传课程图片");
        }

        //添加课程预发布记录
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        //课程基本信息加部分营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseService.getCourseBaseInfo(courseId);
        BeanUtils.copyProperties(courseBaseInfo,coursePublishPre);
        //课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //转为json
        String courseMarketJson = JSON.toJSONString(courseMarket);
        //将课程营销信息json数据放入课程预发布表
        coursePublishPre.setMarket(courseMarketJson);

        //查询课程计划信息
        List<TeachPlanDto> teachplanTree = teachplanService.findTeachPlanTree(courseId);
        if(teachplanTree.size()<=0){
            LearningException.cast("提交失败，还没有添加课程计划");
        }
        //转json
        String teachplanTreeString = JSON.toJSONString(teachplanTree);
        coursePublishPre.setTeachplan(teachplanTreeString);

        //设置预发布记录状态,已提交
        coursePublishPre.setStatus("202003");
        //教学机构id
        coursePublishPre.setCompanyId(companyId);
        //提交时间
        coursePublishPre.setCreateDate(LocalDateTime.now());
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPreUpdate == null){
            //添加课程预发布记录
            coursePublishPreMapper.insert(coursePublishPre);
        }else{
            coursePublishPreMapper.updateById(coursePublishPre);
        }

        //更新课程基本表的审核状态
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);

    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {
        //约束校验
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPreMapper == null){
            LearningException.cast("请先提交课程审核");
        }
        //本机构只能提交本机构的课程
        if(!coursePublishPre.getCompanyId().equals(companyId)){
            LearningException.cast("本机构只能提交本机构的课程");
        }
        //课程审核状态
        String status = coursePublishPre.getStatus();
        if(!"202004".equals(status)){
            LearningException.cast("操作失败, 课程审核通过方可发布");
        }
        //保存课程发布信息
        saveCoursePublish(courseId);
        //保存消息表
        saveCoursePublishMessage(courseId);
        //删除课程预发布表对应记录
        coursePublishPreMapper.deleteById(courseId);
    }

    /**
     * 保存课程发布信息
     * @param courseId
     */
    private void saveCoursePublishMessage(Long courseId) {
//        MqMessage coursePublish = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
//        if(coursePublish == null){
//            LearningException.cast(CommonError.UNKOWN_ERROR);
//        }
    }

    /**
     *
     * 保存消息表信息
     * @param courseId
     */
    private void saveCoursePublish(Long courseId) {
//        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
//        if(mqMessage == null){
//            LearningException.cast(CommonError.UNKOWN_ERROR);
//        }
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if(coursePublishPre == null){
            LearningException.cast("课程预发布数据为空");
        }
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        coursePublish.setStatus("203002");
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if(coursePublishUpdate == null){
            coursePublishMapper.insert(coursePublish);
        }else{
            coursePublishMapper.updateById(coursePublish);
        }
        //更新课程基本表的发布状态
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }
}
